from datetime import datetime
from ..models import Field, Sensor, SensorData

class DecisionService:
    def generate_decision(self, decision_type, field_id):
        if decision_type == 'irrigation':
            return self.generate_irrigation_decision(field_id)
        elif decision_type == 'fertilizer':
            return self.generate_fertilizer_decision(field_id)
        elif decision_type == 'pesticide':
            return self.generate_pesticide_decision(field_id)
        else:
            raise ValueError('Invalid decision type')

    def generate_irrigation_decision(self, field_id):
        # 获取土壤墒情数据
        sensors = Sensor.find_by_field(field_id)
        moisture_data = []
        for sensor in sensors:
            if sensor.device_type == 'soil_moisture':
                data = SensorData.find_by_sensor(str(sensor._id), limit=1)
                if data:
                    moisture_data.append(data[0].value)
        
        # 分析结果
        analysis_result = {
            'soil_moisture': sum(moisture_data) / len(moisture_data) if moisture_data else None,
            'weather_forecast': '晴天',
            'last_irrigation': '3天前'
        }
        
        # 决策建议
        recommendation = {
            'should_irrigate': True if analysis_result['soil_moisture'] and analysis_result['soil_moisture'] < 30 else False,
            'recommended_amount': 30,  # mm
            'recommended_time': datetime.now().isoformat()
        }
        
        return analysis_result, recommendation

    def generate_fertilizer_decision(self, field_id):
        # 示例实现
        analysis_result = {
            'soil_nutrients': {
                'N': 20,
                'P': 15,
                'K': 18
            },
            'growth_stage': '营养生长期'
        }
        
        recommendation = {
            'fertilizer_type': '复合肥',
            'amount': 50,  # kg/亩
            'method': '撒施'
        }
        
        return analysis_result, recommendation

    def generate_pesticide_decision(self, field_id):
        # 示例实现
        analysis_result = {
            'pest_type': '蚜虫',
            'severity': '中度',
            'affected_area': 30  # %
        }
        
        recommendation = {
            'pesticide': '啶虫脒',
            'concentration': '2000倍液',
            'spray_method': '喷雾',
            'protective_measures': ['防护服', '口罩', '手套']
        }
        
        return analysis_result, recommendation 